# coding=utf-8
# copyright (c) 2025 tencent inc. all rights reserved.
# guanyouhe@tencent.com

from typing import Optional, List
from dataclasses import dataclass, field

import torch
from torch import nn
from torch import Tensor
import torch.nn.functional as F
import torch.distributed

from megatron.core import mpu
from megatron.core.models.common.vision_module.vision_module import VisionModule
from megatron.core.transformer.transformer_block import TransformerBlock
from megatron.core import InferenceParams, tensor_parallel
from megatron.core.models.vision.multimodal_projector import MultimodalProjector

from megatron.core.transformer.spec_utils import ModuleSpec
from megatron.core import tensor_parallel

from gpatch.core.packed_seq_params import GpatchPackedSeqParams
from gpatch.core.tensor_parallel.mappings import gather_from_any_dim
from gpatch.core.transformer.transformer_config import GpatchTransformerConfig
from gpatch.core.extensions.llama3_cp_memory_efficient_attention import MemoryEfficientAttention
from gpatch.core.utils import split_data_ulysses_cp_rank
from gpatch.core.extensions.cp_utils import (
    llama3_prepare_memory_efficient_mask,
    llama3_prepare_cu_kv_slice,
)


@dataclass
class Qwen2VLTransformerConfig(GpatchTransformerConfig):

    rotary_base: int = None
    rotary_scaling_factor: int = None
    max_position_embeddings: int = None
    moe_aux_loss_coeff: float = 0.0

    seq_length: int = 1
    temporal_patch_size: int = 1
    patch_size: int = 1
    in_channels: int = 1
    spatial_merge_size: int = 1


# qwen2.5-vl
@dataclass
class Qwen2P5VLTransformerConfig(GpatchTransformerConfig):

    rotary_base: int = None
    rotary_scaling_factor: int = None
    max_position_embeddings: int = None
    moe_aux_loss_coeff: float = 0.0

    seq_length: int = 1
    temporal_patch_size: int = 1
    patch_size: int = 1
    in_channels: int = 1
    spatial_merge_size: int = 1

    qwen2_window_size: int = 112
    fullatt_block_indexes: List[int] = field(default_factory=lambda: [7, 15, 23, 31])


# copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
# NOTE(guanyouhe): 不支持TP
class PatchEmbed(nn.Module):

    def __init__(
        self,
        patch_size: int = 14,
        temporal_patch_size: int = 2,
        in_channels: int = 3,
        embed_dim: int = 1152,
    ) -> None:
        super().__init__()
        self.patch_size = patch_size
        self.temporal_patch_size = temporal_patch_size
        self.in_channels = in_channels
        self.embed_dim = embed_dim

        kernel_size = [temporal_patch_size, patch_size, patch_size]
        self.proj = nn.Conv3d(in_channels,
                              embed_dim,
                              kernel_size=kernel_size,
                              stride=kernel_size,
                              bias=False)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        target_dtype = self.proj.weight.dtype
        hidden_states = hidden_states.view(-1, self.in_channels, self.temporal_patch_size,
                                           self.patch_size, self.patch_size)
        hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
        return hidden_states


# copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
class VisionRotaryEmbedding(nn.Module):

    def __init__(self, dim: int, theta: float = 10000.0) -> None:
        super().__init__()
        inv_freq = 1.0 / (theta**(torch.arange(0, dim, 2, dtype=torch.float) / dim))
        self.inv_freq = inv_freq.cuda()

    def forward(self, seqlen: int) -> torch.Tensor:
        seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
        freqs = torch.outer(seq, self.inv_freq)
        return freqs


class Qwen2VisionModel(VisionModule):
    """Qwen2 ViT vision model, adapted from CLIPViTModel to support Naive Dynamic Resolution.

    Args:
        transformer_config (Qwen2VLTransformerConfig): Transformer config.
        transformer_layer_spec (ModuleSpec): Specifies module to use for transformer layers.
        ln_pre_impl (ModuleSpec or type): Specifies the layer norm type to use for ln_pre.
        add_class_token (bool, optional): Include a class token. Defaults to True.
        class_token_len (int): Class token length. Defaults to 1 but 8 may be faster.
        patch_dim (int): Image patch size.
        img_h (int): Input image height.
        img_w (int): Input image width.
    """

    def __init__(self,
                 transformer_config: Qwen2VLTransformerConfig,
                 transformer_layer_spec: ModuleSpec,
                 projection_config: Qwen2VLTransformerConfig,
                 projection_layer_spec: ModuleSpec,
                 projection_type: str = "mlp",
                 pre_process: bool = True,
                 post_process: bool = False) -> None:
        super().__init__(config=transformer_config)
        # 限制两者的sequence-parallel一致
        assert transformer_config.sequence_parallel == projection_config.sequence_parallel

        self.spatial_merge_size = transformer_config.spatial_merge_size

        embed_dim = transformer_config.hidden_size
        num_heads = transformer_config.num_attention_heads
        temporal_patch_size = transformer_config.temporal_patch_size
        patch_size = transformer_config.patch_size
        in_channels = transformer_config.in_channels

        self.max_sequence_length = transformer_config.seq_length
        self.patch_embed = PatchEmbed(
            patch_size=patch_size,
            temporal_patch_size=temporal_patch_size,
            in_channels=in_channels,
            embed_dim=embed_dim,
        )

        head_dim = embed_dim // num_heads
        self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)

        self.pre_process = pre_process
        self.post_process = post_process
        self.use_xformers = transformer_layer_spec.submodules.self_attention.submodules.core_attention == MemoryEfficientAttention

        # Transformer layers.
        # TODO: Follow-up changes will make pre and post_process configurable. They are needed for supporting pipeline parallelism.
        # NOTE: a final layer norm and/or linear layer present in some implementations are omitted here.
        self.decoder = TransformerBlock(config=transformer_config,
                                        spec=transformer_layer_spec,
                                        pre_process=self.pre_process,
                                        post_process=self.post_process,
                                        post_layer_norm=True)

        self.merge_hidden_size = projection_config.ffn_hidden_size
        self.square_merge_size = self.merge_hidden_size // embed_dim

        if self.post_process:
            self.projection = MultimodalProjector(projection_config, projection_layer_spec,
                                                  projection_type,
                                                  projection_config.ffn_hidden_size)
        else:
            self.projection = None

        self.input_tensor = None

    def set_input_tensor(self, input_tensor: torch.Tensor) -> None:
        """Sets input tensor to the model.

        Args:
            input_tensor (Tensor): Sets the input tensor for the model.
        """
        if self.pre_process:  # always True
            self.input_tensor = input_tensor
        else:
            raise NotImplementedError()

    def rot_pos_emb(self, grid_thw):
        pos_ids = []
        for t, h, w in grid_thw:
            hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
            hpos_ids = hpos_ids.reshape(
                h // self.spatial_merge_size,
                self.spatial_merge_size,
                w // self.spatial_merge_size,
                self.spatial_merge_size,
            )
            hpos_ids = hpos_ids.permute(0, 2, 1, 3)
            hpos_ids = hpos_ids.flatten()

            wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
            wpos_ids = wpos_ids.reshape(
                h // self.spatial_merge_size,
                self.spatial_merge_size,
                w // self.spatial_merge_size,
                self.spatial_merge_size,
            )
            wpos_ids = wpos_ids.permute(0, 2, 1, 3)
            wpos_ids = wpos_ids.flatten()
            pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
        pos_ids = torch.cat(pos_ids, dim=0).to(grid_thw.device)
        max_grid_size = grid_thw[:, 1:].max()
        rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size).to(grid_thw.device)
        rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
        return rotary_pos_emb

    def forward(
        self,
        vision_data: Optional[torch.Tensor],
        grid_thw: torch.Tensor,
        image_padded: bool,
        inference_params: Optional[InferenceParams] = None,
        extra_block_kwargs: dict = None,
    ) -> torch.Tensor:
        """Forward function of the Qwen2 Vision Model. This function passes the input tensors
        through the embedding layer and then the transformer.

        Args:
            x (torch.Tensor): input image/video data of shape [n_tokens, n_dims]
            grid_thw (torch.Tensor): the size tensor indicates grid size of each image/frame

        Returns:
            x (torch.Tensor): output after final transformer block of shape [b, s, h].
        """
        # NOTE: each epp stage should have thw_grids to build PackedSedParams
        assert grid_thw is not None
        if self.input_tensor is not None:
            vision_data = self.input_tensor[:, None]
            self.input_tensor = None
        # otherwise, either vision_data is not None or in EPP intermediate stage
        if inference_params is not None:
            raise NotImplementedError()

        # Rotary positional embeddings (embedding is None for PP intermediate devices)
        rotary_pos_emb = None
        if self.pre_process:
            vision_data = self.patch_embed(vision_data)[:, None]
            rotary_pos_emb = self.rot_pos_emb(grid_thw)[:, None, None, :].repeat(1, 1, 1, 2)
            if self.config.context_parallel_size > 1:
                rotary_pos_emb = split_data_ulysses_cp_rank(rotary_pos_emb,
                                                            self.config.context_parallel_size, 0)
            if self.config.sequence_parallel:
                vision_data = tensor_parallel.scatter_to_sequence_parallel_region(vision_data)

        if self.use_xformers:
            cu_seqlens = torch.zeros(grid_thw.shape[0] + 1, dtype=torch.int, device="cpu")
            cu_seqlens[1:] = torch.prod(grid_thw, dim=-1).cumsum(dim=0)
            attention_mask = llama3_prepare_memory_efficient_mask(
                cu_seqlens, False, mpu.get_context_parallel_rank(),
                mpu.get_context_parallel_world_size(), grid_thw.device)
            kv_slice = None
            if mpu.get_context_parallel_world_size() > 1:
                kv_slice = llama3_prepare_cu_kv_slice(cu_seqlens, False,
                                                      mpu.get_context_parallel_rank(),
                                                      mpu.get_context_parallel_world_size())
            heads_k_stride = self.config.context_parallel_heads_kv_stride
            if heads_k_stride is None:
                heads_k_stride = self.config.num_attention_heads
            heads_k_stride = heads_k_stride // self.config.tensor_model_parallel_size
            packed_seq_params = GpatchPackedSeqParams(
                cu_seqlens_q=cu_seqlens,
                cu_seqlens_kv=cu_seqlens,
                qkv_format='thd',
                use_zigzag=False,
                kv_slice=kv_slice,
                heads_k_stride=heads_k_stride,
            )
        else:
            attention_mask = None
            packed_seq_params = self.build_packed_seq_params(grid_thw)

        hidden_states = self.decoder(
            hidden_states=vision_data,
            attention_mask=attention_mask,
            inference_params=inference_params,
            rotary_pos_emb=rotary_pos_emb,
            packed_seq_params=packed_seq_params,
            **(extra_block_kwargs or {}),
        )

        if not self.post_process:
            return hidden_states

        output = self.projection(hidden_states.view(-1, self.merge_hidden_size))

        if self.projection.config.sequence_parallel:
            output = tensor_parallel.gather_from_sequence_parallel_region(output)

        if self.config.context_parallel_size > 1:
            output = gather_from_any_dim(
                output,
                gather_dim=0,
                comm_group=mpu.get_context_parallel_group(),
            )

        if image_padded:
            padded_thw = grid_thw[-1].tolist()
            padded_seqlen = 1
            for ele in padded_thw:
                padded_seqlen *= ele
            assert padded_seqlen % 4 == 0
            padded_seqlen = padded_seqlen // 4
            output = output[:-padded_seqlen]

        return output

    def build_packed_seq_params(self, grid_thw: torch.Tensor) -> GpatchPackedSeqParams:
        cu_seqlens = torch.zeros(grid_thw.shape[0] + 1, dtype=torch.int, device=grid_thw.device)
        cu_seqlens[1:] = torch.prod(grid_thw, dim=-1).cumsum(dim=0)
        return GpatchPackedSeqParams(cu_seqlens_q=cu_seqlens,
                                     cu_seqlens_kv=cu_seqlens,
                                     qkv_format='thd')


# qwen2.5-vl
class Qwen2P5VisionModel(VisionModule):
    """Qwen2 ViT vision model, adapted from CLIPViTModel to support Naive Dynamic Resolution.

    Args:
        transformer_config (Qwen2P5VLTransformerConfig): Transformer config.
        transformer_layer_spec (ModuleSpec): Specifies module to use for transformer layers.
        ln_pre_impl (ModuleSpec or type): Specifies the layer norm type to use for ln_pre.
        add_class_token (bool, optional): Include a class token. Defaults to True.
        class_token_len (int): Class token length. Defaults to 1 but 8 may be faster.
        patch_dim (int): Image patch size.
        img_h (int): Input image height.
        img_w (int): Input image width.
    """

    def __init__(self,
                 transformer_config: Qwen2P5VLTransformerConfig,
                 transformer_layer_spec: ModuleSpec,
                 projection_config: Qwen2P5VLTransformerConfig,
                 projection_layer_spec: ModuleSpec,
                 projection_type: str = "mlp",
                 pre_process: bool = True,
                 post_process: bool = False) -> None:
        super().__init__(config=transformer_config)
        # 限制两者的sequence-parallel一致
        assert transformer_config.sequence_parallel == projection_config.sequence_parallel

        self.spatial_merge_size = transformer_config.spatial_merge_size
        self.patch_size = transformer_config.patch_size
        self.qwen2_window_size = transformer_config.qwen2_window_size
        self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size

        embed_dim = transformer_config.hidden_size
        num_heads = transformer_config.num_attention_heads
        temporal_patch_size = transformer_config.temporal_patch_size
        in_channels = transformer_config.in_channels

        self.max_sequence_length = transformer_config.seq_length
        self.patch_embed = PatchEmbed(
            patch_size=self.patch_size,
            temporal_patch_size=temporal_patch_size,
            in_channels=in_channels,
            embed_dim=embed_dim,
        )

        head_dim = embed_dim // num_heads
        self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)

        self.pre_process = pre_process
        self.post_process = post_process
        self.use_xformers = transformer_layer_spec.submodules.self_attention.submodules.core_attention == MemoryEfficientAttention

        # Transformer layers.
        # TODO: Follow-up changes will make pre and post_process configurable. They are needed for supporting pipeline parallelism.
        # NOTE: a final layer norm and/or linear layer present in some implementations are omitted here.
        self.decoder = TransformerBlock(
            config=transformer_config,
            spec=transformer_layer_spec,
            pre_process=self.pre_process,
            post_process=self.post_process,
            post_layer_norm=True,
        )

        self.merge_hidden_size = projection_config.ffn_hidden_size
        self.square_merge_size = self.merge_hidden_size // embed_dim

        if self.post_process:
            self.projection = MultimodalProjector(projection_config, projection_layer_spec,
                                                  projection_type,
                                                  projection_config.ffn_hidden_size)
        else:
            self.projection = None

        self.input_tensor = None

    def set_input_tensor(self, input_tensor: torch.Tensor) -> None:
        """Sets input tensor to the model.

        Args:
            input_tensor (Tensor): Sets the input tensor for the model.
        """
        if self.pre_process:  # always True
            self.input_tensor = input_tensor
        else:
            raise NotImplementedError()

    def rot_pos_emb(self, grid_thw):
        pos_ids = []
        for t, h, w in grid_thw:
            hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
            hpos_ids = hpos_ids.reshape(
                h // self.spatial_merge_size,
                self.spatial_merge_size,
                w // self.spatial_merge_size,
                self.spatial_merge_size,
            )
            hpos_ids = hpos_ids.permute(0, 2, 1, 3)
            hpos_ids = hpos_ids.flatten()

            wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
            wpos_ids = wpos_ids.reshape(
                h // self.spatial_merge_size,
                self.spatial_merge_size,
                w // self.spatial_merge_size,
                self.spatial_merge_size,
            )
            wpos_ids = wpos_ids.permute(0, 2, 1, 3)
            wpos_ids = wpos_ids.flatten()
            pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
        pos_ids = torch.cat(pos_ids, dim=0).to(grid_thw.device)
        max_grid_size = grid_thw[:, 1:].max()
        rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size).to(grid_thw.device)
        rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
        return rotary_pos_emb

    def get_window_index(self, grid_thw):
        window_index: list = []
        cu_window_seqlens: list = [0]
        window_index_id = 0
        vit_merger_window_size = self.qwen2_window_size // self.spatial_merge_size // self.patch_size

        for grid_t, grid_h, grid_w in grid_thw:
            llm_grid_h, llm_grid_w = (
                grid_h // self.spatial_merge_size,
                grid_w // self.spatial_merge_size,
            )
            index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(
                grid_t, llm_grid_h, llm_grid_w)
            pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size
            pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size
            num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size
            num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size
            index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100)
            index_padded = index_padded.reshape(
                grid_t,
                num_windows_h,
                vit_merger_window_size,
                num_windows_w,
                vit_merger_window_size,
            )
            index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape(
                grid_t,
                num_windows_h * num_windows_w,
                vit_merger_window_size,
                vit_merger_window_size,
            )
            seqlens = (index_padded != -100).sum([2, 3]).reshape(-1)
            index_padded = index_padded.reshape(-1)
            index_new = index_padded[index_padded != -100]
            window_index.append(index_new + window_index_id)
            cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1]
            cu_window_seqlens.extend(cu_seqlens_tmp.tolist())
            window_index_id += (grid_t * llm_grid_h * llm_grid_w).item()
        window_index = torch.cat(window_index, dim=0)

        return window_index, cu_window_seqlens

    def forward(
        self,
        vision_data: Optional[torch.Tensor],
        grid_thw: torch.Tensor,
        image_padded: bool,
        inference_params: Optional[InferenceParams] = None,
        extra_block_kwargs: dict = None,
    ) -> torch.Tensor:
        """Forward function of the Qwen2 Vision Model. This function passes the input tensors
        through the embedding layer and then the transformer.

        Args:
            x (torch.Tensor): input image/video data of shape [n_tokens, n_dims]
            grid_thw (torch.Tensor): the size tensor indicates grid size of each image/frame

        Returns:
            x (torch.Tensor): output after final transformer block of shape [b, s, h].
        """
        # NOTE: each epp stage should have thw_grids to build PackedSedParams
        assert grid_thw is not None
        if self.input_tensor is not None:
            vision_data = self.input_tensor
            self.input_tensor = None
        # otherwise, either vision_data is not None or in EPP intermediate stage
        if inference_params is not None:
            raise NotImplementedError()

        # Rotary positional embeddings (embedding is None for PP intermediate devices)
        rotary_pos_emb = None
        if self.pre_process:
            vision_data = self.patch_embed(vision_data)
            rotary_pos_emb = self.rot_pos_emb(grid_thw)
            window_index, cu_window_seqlens = self.get_window_index(grid_thw)
            cu_window_seqlens = torch.tensor(
                cu_window_seqlens,
                device=vision_data.device,
                dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
            )
            cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens)

            seq_len, _ = vision_data.size()
            vision_data = vision_data.reshape(seq_len // self.spatial_merge_unit,
                                              self.spatial_merge_unit, -1)
            vision_data = vision_data[window_index, :, :]
            vision_data = vision_data.reshape(seq_len, -1)
            vision_data = vision_data[:, None]

            rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit,
                                                    self.spatial_merge_unit, -1)
            rotary_pos_emb = rotary_pos_emb[window_index, :, :]
            rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1)
            rotary_pos_emb = rotary_pos_emb[:, None, None, :].repeat(1, 1, 1, 2)

            if self.config.context_parallel_size > 1:
                rotary_pos_emb = split_data_ulysses_cp_rank(rotary_pos_emb,
                                                            self.config.context_parallel_size, 0)
                vision_data = split_data_ulysses_cp_rank(vision_data,
                                                         self.config.context_parallel_size, 0)
            if self.config.sequence_parallel:
                vision_data = tensor_parallel.scatter_to_sequence_parallel_region(vision_data)

        if self.use_xformers:
            cu_seqlens0 = torch.zeros(grid_thw.shape[0] + 1, dtype=torch.int, device="cpu")
            cu_seqlens0[1:] = torch.prod(grid_thw, dim=-1).cumsum(dim=0)
            attention_mask0 = llama3_prepare_memory_efficient_mask(
                cu_seqlens0, False, mpu.get_context_parallel_rank(),
                mpu.get_context_parallel_world_size(), grid_thw.device)
            kv_slice0 = None
            if mpu.get_context_parallel_world_size() > 1:
                kv_slice0 = llama3_prepare_cu_kv_slice(cu_seqlens0, False,
                                                       mpu.get_context_parallel_rank(),
                                                       mpu.get_context_parallel_world_size())

            heads_k_stride = self.config.context_parallel_heads_kv_stride
            if heads_k_stride is None:
                heads_k_stride = self.config.num_attention_heads
            heads_k_stride = heads_k_stride // self.config.tensor_model_parallel_size
            packed_seq_params0 = GpatchPackedSeqParams(
                cu_seqlens_q=cu_seqlens0,
                cu_seqlens_kv=cu_seqlens0,
                qkv_format='thd',
                use_zigzag=False,
                kv_slice=kv_slice0,
                heads_k_stride=heads_k_stride,
            )
            attention_mask1 = llama3_prepare_memory_efficient_mask(
                cu_window_seqlens, False, mpu.get_context_parallel_rank(),
                mpu.get_context_parallel_world_size(), grid_thw.device)
            kv_slice1 = None
            if mpu.get_context_parallel_world_size() > 1:
                kv_slice1 = llama3_prepare_cu_kv_slice(cu_window_seqlens, False,
                                                       mpu.get_context_parallel_rank(),
                                                       mpu.get_context_parallel_world_size())
            packed_seq_params1 = GpatchPackedSeqParams(
                cu_seqlens_q=cu_window_seqlens,
                cu_seqlens_kv=cu_window_seqlens,
                qkv_format='thd',
                use_zigzag=False,
                kv_slice=kv_slice1,
                heads_k_stride=heads_k_stride,
            )

            attention_mask = (attention_mask0, attention_mask1)
            packed_seq_params = (packed_seq_params0, packed_seq_params1)
        else:
            attention_mask = None
            packed_seq_params = (self.build_packed_seq_params(grid_thw),
                                 GpatchPackedSeqParams(cu_seqlens_q=cu_window_seqlens,
                                                       cu_seqlens_kv=cu_window_seqlens,
                                                       qkv_format='thd'))

        hidden_states = self.decoder(
            hidden_states=vision_data,
            attention_mask=attention_mask,
            inference_params=inference_params,
            rotary_pos_emb=rotary_pos_emb,
            packed_seq_params=packed_seq_params,
            **(extra_block_kwargs or {}),
        )

        if not self.post_process:
            return hidden_states

        output = self.projection(hidden_states.view(-1, self.merge_hidden_size))

        if self.projection.config.sequence_parallel:
            output = tensor_parallel.gather_from_sequence_parallel_region(output)

        if self.config.context_parallel_size > 1:
            output = gather_from_any_dim(
                output,
                gather_dim=0,
                comm_group=mpu.get_context_parallel_group(),
            )

        reverse_indices = torch.argsort(window_index)
        output = output[reverse_indices, :]

        if image_padded:
            padded_thw = grid_thw[-1].tolist()
            padded_seqlen = 1
            for ele in padded_thw:
                padded_seqlen *= ele
            assert padded_seqlen % 4 == 0
            padded_seqlen = padded_seqlen // 4
            output = output[:-padded_seqlen]

        return output

    def build_packed_seq_params(self, grid_thw: torch.Tensor) -> GpatchPackedSeqParams:
        cu_seqlens = torch.zeros(grid_thw.shape[0] + 1, dtype=torch.int, device=grid_thw.device)
        cu_seqlens[1:] = torch.prod(grid_thw, dim=-1).cumsum(dim=0)
        return GpatchPackedSeqParams(cu_seqlens_q=cu_seqlens,
                                     cu_seqlens_kv=cu_seqlens,
                                     qkv_format='thd')
